﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Threading;
using Microsoft.Phone.BackgroundAudio;
using Samples.Radio.Agent;
using Samples.Radio.Agent.Data;
using Samples.Radio.Agent.Model;
using WindowsPhoneAudioStreaming.Audio.Streaming;
using Samples.Radio.Data;
using Samples.Radio.Helpers;
using Samples.Radio.Pages.Program;

namespace Samples.Radio.Pages.Main
{
    public class MainPageViewModel : ViewModelBase
    {
        private Mutex progressMutex = new Mutex(false, "BufferProgress");

        public event EventHandler<DualParameterEventArgs<BufferStatus, double>> BufferStatusChanged;
        //private bool isBuffering;

        DispatcherTimer _UIRefreshTimer;

        private bool _IsPlayerIndeterminate;
        bool stopCurrentTrack = false;

        public bool IsPlayerIndeterminate
        {
            get { return _IsPlayerIndeterminate; }
            set
            {
                if (IsPlayerIndeterminate == value) return;
                _IsPlayerIndeterminate = value;
                RaisePropertyChanged(() => IsPlayerIndeterminate);
            }
        }

        private double _MaximumPlayerDurationSeconds;
        /// <summary>
        /// what is the maximum number of seconds that can elapse in the player
        /// </summary>
        public double MaximumPlayerDurationSeconds
        {
            get { return _MaximumPlayerDurationSeconds; }
            set
            {
                if (MaximumPlayerDurationSeconds == value) return;
                _MaximumPlayerDurationSeconds = value;
                RaisePropertyChanged(() => MaximumPlayerDurationSeconds);
            }
        }

        private bool _IsPlayEnabled;
        /// <summary>
        /// Is 'play' enabled
        /// </summary>
        public bool IsPlayEnabled
        {
            get { return _IsPlayEnabled; }
            set
            {
                if (IsPlayEnabled == value) return;
                _IsPlayEnabled = value;
                RaisePropertyChanged(() => IsPlayEnabled);
            }
        }


        private bool _IsPauseEnabled;
        /// <summary>
        /// Is 'pause' enabled
        /// </summary>
        public bool IsPauseEnabled
        {
            get { return _IsPauseEnabled; }
            set
            {
                if (IsPauseEnabled == value) return;
                _IsPauseEnabled = value;
                RaisePropertyChanged(() => IsPauseEnabled);
            }
        }

        private bool _IsPreviousEnabled;
        /// <summary>
        /// Is the 'previous' track enabled
        /// </summary>
        public bool IsPreviousEnabled
        {
            get { return _IsPreviousEnabled; }
            set
            {
                if (IsPreviousEnabled == value) return;
                _IsPreviousEnabled = value;
                RaisePropertyChanged(() => IsPreviousEnabled);
            }
        }

        private bool _IsNextEnabled;
        /// <summary>
        /// Is the 'next' track enabled
        /// </summary>
        public bool IsNextEnabled
        {
            get { return _IsNextEnabled; }
            set
            {
                if (IsNextEnabled == value) return;
                _IsNextEnabled = value;
                RaisePropertyChanged(() => IsNextEnabled);
            }
        }


        /// <summary>
        /// Is there data loaded for the application
        /// </summary>
        public bool IsDataLoaded
        {
            get;
            private set;
        }

        public MainPageViewModel(RadioRepository repository, IDispatcher dispatcher, INavigation navigation)
            : base(repository, dispatcher, navigation)
        {
            AddEventWiring(() => Repository.LoadProgramsCompleted += LoadProgramsCompleted,
               () => Repository.LoadProgramsCompleted -= LoadProgramsCompleted);
            AddEventWiring(() => Repository.TrackInformationUpdated += TrackInformationUpdated,
               () => Repository.TrackInformationUpdated -= TrackInformationUpdated);

            CurrentPlaybackMode = RadioSettings.Instance.AudioPlaybackMode;

            // Initialize a timer to update the UI every half-second.
            _UIRefreshTimer = new DispatcherTimer();
            _UIRefreshTimer.Interval = TimeSpan.FromSeconds(0.5);
            _UIRefreshTimer.Tick += UpdateState;

            _LatestSongListTimer = new DispatcherTimer();
            _LatestSongListTimer.Interval = TimeSpan.FromSeconds(60);
            _LatestSongListTimer.Tick += (s, e) =>
            {
                RefreshPlayList();
            };


            this.AudioStreams = new ObservableCollection<TrackViewModel>();
            this.Programs = new ObservableCollection<ProgramViewModel>();
            this.Podcasts = new ObservableCollection<PlaylistTrack>();
            this.Podcasts.CollectionChanged += (s, e) =>
            {
                RaisePropertyChanged(() => HasPodcasts);
                RaisePropertyChanged(() => Podcasts);
                RaisePropertyChanged(() => CurrentPodcastTrack);
            };

            this.Programs.CollectionChanged += (s, e) =>
            {
                GetCurrentProgram();
            };

            BackgroundAudioPlayer.Instance.PlayStateChanged += Instance_PlayStateChanged;
        }


        private void LoadProgramsCompleted(object sender, ParameterEventArgs<ProgramViewModel[]> e)
        {
            if (e == null || e.Parameter1 == null)
            {
                // TODO: Handle errors in loading program data
                return;
            }

            //Get a list of programs
            var progs = (from p in e.Parameter1
                         select p).ToList();

            Programs.Replace(progs);

            ObservableCollection<PodcastViewModel> podcasts = new ObservableCollection<PodcastViewModel>();

            //Download all the podcasts
            progs.ToList().ForEach(
                p =>
                {
                    p.LoadPodcastsCompleted += (s, loadedPodcasts) => {
                        var result = podcasts.Union(loadedPodcasts.Parameter1.ToList()).Select(r => r.ToProgramViewModel(p));
                        
                        FeaturedPodcasts.Replace(result.Take(5));
                        if (FeaturedPodcasts.Count > 0)
                        {
                            FeaturedPodcasts[0].IsFirst = true;
                        }
                    };
                }
                );

            //Now get the items for the 'Featured' section
            var allPodcasts = progs.SelectMany(p => p.Podcasts);
            


        }

        public override void OnNavigatedTo(NavigationEventArgs navigationEventArgs, NavigationContext context, IDictionary<string, object> pageState)
        {
            base.OnNavigatedTo(navigationEventArgs, context, pageState);

            if (!this.IsDataLoaded)
            {
                LoadData();

                // Initialize a timer to update the UI every half-second.
                _UIRefreshTimer = new DispatcherTimer();
                _UIRefreshTimer.Interval = TimeSpan.FromSeconds(0.5);
                _UIRefreshTimer.Tick += UpdateState;

                if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                {
                    // If audio was already playing when the app was launched, update the UI.
                    IsPlayerIndeterminate = false;
                    MaximumPlayerDurationSeconds = BackgroundAudioPlayer.Instance.Track.Duration.TotalSeconds;
                    UpdateButtons(true, false, true, true);
                    UpdateState(null, null);
                }
            }
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                RefreshPlayList();
                RaisePropertyChanged("IsPlayingStream");
                RaisePropertyChanged("IsPlayingPodcasts");
            });
        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            Repository.LoadPrograms();

            AudioStreams = new ObservableCollection<TrackViewModel>(
                Repository.Configuration.Streams.Select(c => c.ToTrackViewModel()).ToList());


            CurrentStream = Repository.CurrentStream.ToTrackViewModel();

            Repository.LoadPlayerService();

            LoadLatestPodcasts();

            this.IsDataLoaded = true;
        }

        private void LoadLatestPodcasts()
        {
            Podcasts.Replace(Repository.NowPlayingService.QueuedTrackList);
        }

        private void TrackInformationUpdated(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
                                       {
                                           RaisePropertyChanged(() => RecentTracks);
                                           RaisePropertyChanged(() => CurrentTrack);
                                       });
        }


        /// <summary>
        /// Updates the status indicators including the State, Track title, 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateState(object sender, EventArgs e)
        {
            try
            {
                _UIRefreshTimer.Stop();

                ThreadPool.QueueUserWorkItem(asyncobj=>UpdateBufferProgress());

               

                CurrentState = string.Format("State: {0}", BackgroundAudioPlayer.Instance.PlayerState);

                if (BackgroundAudioPlayer.Instance.Track != null)
                {
                    //try
                    //{
                    //    var tag = BackgroundAudioPlayer.Instance.Track.Tag;
                    //    ThreadPool.QueueUserWorkItem(asyncobj => UpdateBufferProgress(tag));
                    //}
                    //catch
                    //{
                    //    // Ignore as this is only reporting buffering progress
                    //}
                    CurrentStream = new TrackViewModel(BackgroundAudioPlayer.Instance.Track);
                    



                    if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Unknown
                        && BackgroundAudioPlayer.Instance.PlayerState != PlayState.Paused)
                    {
                        // Set the current position on the ProgressBar.
                        if (BackgroundAudioPlayer.Instance != null && BackgroundAudioPlayer.Instance.Position != null
                            && BackgroundAudioPlayer.Instance.Track != null)
                        {
                            PlayerCurrentSecondsElapsed = BackgroundAudioPlayer.Instance.Position.TotalSeconds;

                            // Update the current playback position.
                            TimeSpan position = new TimeSpan();
                            position = BackgroundAudioPlayer.Instance.Position;
                            CurrentPosition = String.Format("{0:d2}:{1:d2}:{2:d2}", position.Hours, position.Minutes, position.Seconds);

                            if (BackgroundAudioPlayer.Instance.Track.Duration != null)
                            {
                                // Update the time remaining digits.
                                TimeSpan timeRemaining = new TimeSpan();
                                timeRemaining = BackgroundAudioPlayer.Instance.Track.Duration - position;
                                TimeRemaining = String.Format("-{0:d2}:{1:d2}:{2:d2}", timeRemaining.Hours, timeRemaining.Minutes, timeRemaining.Seconds);
                            }
                        }
                        else
                        {
                            PlayerCurrentSecondsElapsed = 0;
                            CurrentPosition = "";
                            TimeRemaining = "";
                        }
                    }
                    else
                    {
                        
                        PlayerCurrentSecondsElapsed = 0;
                        CurrentPosition = "";
                        TimeRemaining = "";
                    }

                }
            }
            catch (Exception ex)
            {
                CurrentState = string.Format("State: {0}", "Stopped");
                Debug.WriteLine(ex.Message);
            }
        }

        private void UpdateBufferProgress()//(string currentStream)
        {
            try
            {

                //if (string.IsNullOrWhiteSpace(currentStream)) return;

                //var bits = currentStream.Split('|');
                //if (bits.Length != 2) return;
                //BufferStatus status = BufferStatus.NotBuffering;
                //double progress=0.0;
                //try
                //{
                //    status = (BufferStatus) Enum.Parse(typeof (BufferStatus), bits[0], true);
                //    progress = double.Parse(bits[1]);
                //}
                //catch (Exception ex)
                //{
                //    return;
                //}



                double progress = 0.0;
                BufferStatus status = BufferStatus.NotBuffering;
                progressMutex.WaitOne();
                try
                {
                    //var track = BackgroundAudioPlayer.Instance.Track;
                    //if(track!=null)
                    //{
                    //    var progressstr = track.Tag.Split('|');
                    //    status = (BufferStatus)Enum.Parse(typeof(BufferStatus), progressstr[0], true);
                    //    progress = double.Parse(progressstr[1]);
                    //}

                    if (IsolatedStorageFile.GetUserStoreForApplication().FileExists("bufferprogress"))
                    {
                        using (
                            var file = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("bufferprogress",
                                                                                                 FileMode.Open,
                                                                                                 FileAccess.Read))
                        using (var reader = new StreamReader(file))
                        {
                            var progressstr = reader.ReadToEnd().Split('|');
                            status = (BufferStatus)Enum.Parse(typeof(BufferStatus), progressstr[0], true);
                            progress = double.Parse(progressstr[1]);

                        }
                    }
                }
                    catch(Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                finally
                {
                    progressMutex.ReleaseMutex();
                }

                Dispatcher.BeginInvoke(() => BufferStatusChanged.SafeRaise(this,
                                                                           status,
                                                                           progress));
            }
            finally
            {
                Dispatcher.BeginInvoke(() => _UIRefreshTimer.Start());
            }
        }

        /// <summary>
        /// Helper method to update the state of the ApplicationBar.Buttons
        /// </summary>
        /// <param name="prevBtnEnabled"></param>
        /// <param name="playBtnEnabled"></param>
        /// <param name="pauseBtnEnabled"></param>
        /// <param name="nextBtnEnabled"></param>
        void UpdateButtons(bool prevBtnEnabled, bool playBtnEnabled, bool pauseBtnEnabled, bool nextBtnEnabled)
        {
            // Set the IsEnabled state of the ApplicationBar.Buttons array
            IsPreviousEnabled = prevBtnEnabled;
            IsPlayEnabled = playBtnEnabled;
            IsPauseEnabled = pauseBtnEnabled;
            IsNextEnabled = nextBtnEnabled;
        }

        /// <summary>
        /// Refresh the playlist to show the most recent tracks
        /// </summary>
        public void RefreshPlayList()
        {
            ThreadPool.QueueUserWorkItem(asyncobj => Repository.NowPlayingService.RefreshCurrentTrack());
        }

        #region Variables

        DispatcherTimer _LatestSongListTimer;

        private const string tileFileName = "/Shared/ShellContent/backgroundart.jpg";

        private PlaybackMode currentPlaybackMode;
        private PlaybackMode CurrentPlaybackMode
        {
            get { return currentPlaybackMode; }
            set
            {
                if (currentPlaybackMode == value) return;
                currentPlaybackMode = value;
                RadioSettings.Instance.AudioPlaybackMode = currentPlaybackMode;
            }
        }

        #endregion

        #region Properties


        #region Collections
        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public IEnumerable<TrackModel> RecentTracks
        {
            get
            {
                if (Repository.NowPlayingService != null && Repository.NowPlayingService.RecentTracks != null)
                {
                    return Repository.NowPlayingService.RecentTracks;
                }

                return new ObservableCollection<TrackModel>();
            }
        }
        public ObservableCollection<TrackViewModel> AudioStreams { get; private set; }
        #endregion

        #region Current Items
        public string Today
        {
            get { return DateTime.Now.DayOfWeek.ToString(); }
        }
        public TrackModel CurrentTrack
        {
            get
            {
                return Repository.NowPlayingService.CurrentTrack;
            }
        }

        private PodcastViewModel _CurrentPodcastTrack;
        public PodcastViewModel CurrentPodcastTrack
        {
            get
            {
                return _CurrentPodcastTrack;
            }
            set
            {
                _CurrentPodcastTrack = value;
                RaisePropertyChanged("CurrentPodcastItem");
            }

        }

        /// <summary>
        /// Has the system got podcast tracks
        /// </summary>
        public bool HasPodcasts
        {
            get
            {
                return this.Podcasts != null && this.Podcasts.Count > 0;
            }
        }

        public ProgramViewModel CurrentProgram
        {
            get
            {
                return GetCurrentProgram();
            }
        }

        private ProgramViewModel _CurrentSelectedProgram;
        public ProgramViewModel CurrentSelectedProgram
        {
            get
            {
                return _CurrentSelectedProgram;
            }
            set
            {
                _CurrentSelectedProgram = value;
                RaisePropertyChanged("CurrentSelectedProgram");
            }
        }

        public bool HasCurrentProgram
        {
            get
            {
                return !String.IsNullOrEmpty(this.CurrentProgram.ProgramName);
            }
        }

        private TrackViewModel _CurrentStream;
        public TrackViewModel CurrentStream
        {
            get
            {
                return _CurrentStream;
            }
            set
            {
                if (CurrentPlaybackMode == PlaybackMode.Streaming
                    && _CurrentStream != null
                    && _CurrentStream.TrackName != value.TrackName)
                {
                    if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                    {
                        //Need to reset the background audio player
                        BackgroundAudioPlayer.Instance.Stop();
                        BackgroundAudioPlayer.Instance.Close();
                    }
                }

                _CurrentStream = value;
                RaisePropertyChanged("CurrentStream");
            }
        }
        #endregion

        #region Podcasts
        /// <summary>
        /// This is the podcast playlist
        /// </summary>
        public ObservableCollection<PlaylistTrack> Podcasts { get; private set; }

        /// <summary>
        /// This is the program list
        /// </summary>
        public ObservableCollection<ProgramViewModel> Programs { get; private set; }

        private ObservableCollection<ProgramViewModel> _featuredPodcasts;

        /// <summary>
        /// This is the list of 'podcasts' that the user can listen to
        /// </summary>
        public ObservableCollection<ProgramViewModel> FeaturedPodcasts
        {
            get
            {
                if (_featuredPodcasts == null)
                {
                    _featuredPodcasts = new ObservableCollection<ProgramViewModel>();
                    _featuredPodcasts.CollectionChanged += FeaturedPodcastsCollectionChanged;
                }
                return _featuredPodcasts;
            }
        }

        private void FeaturedPodcastsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            RaisePropertyChanged(() => FeaturedPodcasts);
            RaisePropertyChanged(() => HasFeaturedProgram);
            RaisePropertyChanged(() => HasSubFeaturedProgram1);
            RaisePropertyChanged(() => HasSubFeaturedProgram2);
            RaisePropertyChanged(() => HasSubFeaturedProgram3);
            RaisePropertyChanged(() => HasSubFeaturedProgram4);
        }

        public bool HasFeaturedProgram
        {
            get
            {
                return FeaturedPodcasts.Count > 0;
            }
        }
        public bool HasSubFeaturedProgram1
        {
            get
            {
                return FeaturedPodcasts.Count > 1;
            }
        }

        public bool HasSubFeaturedProgram2
        {
            get
            {
                return FeaturedPodcasts.Count > 2;
            }
        }

        public bool HasSubFeaturedProgram3
        {
            get
            {
                return FeaturedPodcasts.Count > 3;
            }
        }

        public bool HasSubFeaturedProgram4
        {
            get
            {
                return FeaturedPodcasts.Count > 4;
            }
        }

        #endregion

        #region Station Details
        private string _StationName;
        /// <summary>
        /// What is the name of the radio station/application
        /// </summary>
        public string StationName
        {
            get
            {
                return _StationName;
            }
            set
            {
                _StationName = value;
                RaisePropertyChanged("StationName");
            }
        }

        private string _Slogan;
        /// <summary>
        /// What is the slogan for the radio station/application
        /// </summary>
        public string Slogan
        {
            get
            {
                return _Slogan;
            }
            set
            {
                _Slogan = value;
                RaisePropertyChanged("Slogan");
            }
        }
        #endregion

        #region Player Properties
        public bool IsPlayingStream
        {
            get
            {
                try
                {
                    if (CurrentPlaybackMode == PlaybackMode.Podcast)
                    {
                        return false;
                    }

                    if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                    {
                        return true;
                    }
                }
                catch(Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                return false;
            }
            set
            {
                if(value)
                {
                    PlayStreamingAudio();
                }
                else
                {
                    Pause();
                }
            }
        }

        public bool IsPlayingPodcasts
        {
            get
            {
                if (CurrentPlaybackMode == PlaybackMode.Streaming)
                {
                    return false;
                }

                if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                {
                    return true;
                }

                return false;
            }
        }

        private string _CurrentState;
        /// <summary>
        /// What is the position of the current track
        /// </summary>
        public string CurrentState
        {
            get
            {
                return _CurrentState;
            }
            set
            {
                _CurrentState = value;
                RaisePropertyChanged("CurrentState");
            }
        }

        private string _CurrentPosition;
        public string CurrentPosition
        {
            get
            {
                return _CurrentPosition;
            }
            set
            {
                _CurrentPosition = value;
                RaisePropertyChanged("CurrentPosition");
            }
        }

        private string _TimeRemaining;
        /// <summary>
        /// What is the time remaining on the current track
        /// </summary>
        public string TimeRemaining
        {
            get
            {
                return _TimeRemaining;
            }
            set
            {
                _TimeRemaining = value;
                RaisePropertyChanged("TimeRemaining");
            }
        }





        private double _PlayerCurrentSecondsElapsed;
        /// <summary>
        /// How many seconds have currently elapsed in the player
        /// </summary>
        public double PlayerCurrentSecondsElapsed
        {
            get
            {
                return _PlayerCurrentSecondsElapsed;
            }
            set
            {
                _PlayerCurrentSecondsElapsed = value;
                RaisePropertyChanged("PlayerCurrentSecondsElapsed");
            }
        }


        #endregion
        
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor for the application
        /// </summary>
        //public MainViewModel()
        //{

        //}
        #endregion

        #region Public Methods
        /// <summary>
        /// Method fired when the page/view is loaded
        /// </summary>


        /// <summary>
        /// Play/start the current audio stream
        /// </summary>
        public void PlayStreamingAudio()
        {
            _UIRefreshTimer.Start();

            LoadStreamingMode();

            BackgroundAudioPlayer.Instance.Play();
            RefreshPlayList();
            
        }

        /// <summary>
        /// Switch to listen to podcasts instead of audio streams
        /// </summary>
        public void PlayPodcasts()
        {
            LoadPodcastMode();

            BackgroundAudioPlayer.Instance.Play();

        }

        /// <summary>
        /// Pause the current audio stream
        /// </summary>
        public void Pause()
        {
            BackgroundAudioPlayer.Instance.Pause();
            
            stopCurrentTrack = true;

            RefreshPlayList();

        }
        
        /// <summary>
        /// Clears the playlist and plays the current track
        /// </summary>
        public void ClearPlaylistAndPlayCurrentTrack()
        {
            //this.Podcasts.Add(CurrentPodcastTrack);
            LoadPodcastMode();
            PlayPodcasts();
        }

        #endregion

        #region Private Method

        /// <summary>
        /// Load the background audio to play in podcast mode
        /// </summary>
        private void LoadPodcastMode()
        {
            if (CurrentPlaybackMode == PlaybackMode.Streaming)
            {
                BackgroundAudioPlayer.Instance.Stop();
                BackgroundAudioPlayer.Instance.Close();
                CurrentPlaybackMode = PlaybackMode.Podcast;
            }
        }

        /// <summary>
        /// Load the player into streaming mode
        /// </summary>
        private void LoadStreamingMode()
        {
            if (CurrentPlaybackMode == PlaybackMode.Podcast)
            {
                BackgroundAudioPlayer.Instance.Stop();
                BackgroundAudioPlayer.Instance.Close();
                CurrentPlaybackMode = PlaybackMode.Streaming;
            }
        }



        /// <summary>
        /// Get the current program
        /// </summary>
        /// <returns></returns>
        private ProgramViewModel GetCurrentProgram()
        {
            TimeSpan timeNow = DateTime.Now.TimeOfDay;
            var currentProgram = Programs.FirstOrDefault(p => p.StartTimeSpan.CompareTo(timeNow) <= 0
                && p.EndTimeSpan.CompareTo(timeNow) >= 0);

            if (currentProgram != null)
            {
                return currentProgram;
            }
            else
            {
                return new ProgramViewModel()
                {
                    ProgramName = "No specified program information",
                    ProgramSlogan = "could be found",
                    Description = "Please check the programs page for available programs"
                };
            }
        }

        #endregion

        #region Events



        /// <summary>
        /// PlayStateChanged event handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            try
            {
                switch (BackgroundAudioPlayer.Instance.PlayerState)
                {
                    case PlayState.Playing:
                        // Update the UI.
                        IsPlayerIndeterminate = false;
                        MaximumPlayerDurationSeconds = BackgroundAudioPlayer.Instance.Track.Duration.TotalSeconds;
                        UpdateButtons(true, false, true, true);
                        UpdateState(null, null);

                        // Start the timer for updating the UI.
                        _UIRefreshTimer.Start();
                        RaisePropertyChanged("IsPlayingStream");
                        RaisePropertyChanged("IsPlayingPodcasts");
                        break;

                    case PlayState.Paused:
                        // Update the UI.
                        UpdateButtons(true, true, false, true);
                        UpdateState(null, null);

                        if ((BackgroundAudioPlayer.Instance.PlayerState == PlayState.Paused) && stopCurrentTrack)
                        {
                            Debug.WriteLine("Stop Current Track");
                            BackgroundAudioPlayer.Instance.Stop();

                            BackgroundAudioPlayer.Instance.Close();
                            stopCurrentTrack = false;
                        }


                        // Stop the timer for updating the UI.
                        //_UIRefreshTimer.Stop();
                        break;
                        //case PlayState.BufferingStarted:
                        //isBuffering = true;
                        //BufferStatusChanged.SafeRaise(this, true,BackgroundAudioPlayer.Instance.BufferingProgress);
                        //break;
                        //case PlayState.BufferingStopped:
                        //isBuffering = false;
                        //BufferStatusChanged.SafeRaise(this, false, 0.0);
                        //break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                UpdateButtons(true, true, false, true);
                UpdateState(null, null);
                // Stop the timer for updating the UI.
                _UIRefreshTimer.Stop();
            }
        }


        #endregion

        public void DisplayFeaturedProgram(ProgramViewModel program)
        {
            Navigation.Navigate(typeof(ProgramPage), new NavigationParameter("ProgramName", program.ProgramName));
        }
    }
}
